import { Router } from '@angular/router';
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class HttpServices {

      constructor(
            private http: Http
      ) { }

      //HTTP get方法
      get(url): Observable<any> {
            return this.http.get(url)
                  .map(this.extractData)
                  .catch(this.handleError);
      }
      getP(url): Promise<any> {
            return this.http.get(url)
                  .toPromise()
                  .then(this.extractData)
                  .catch(this.handleError);
      }


      //HTTP post方法
      post(url, data): Observable<any> {
            //设置头
            let headers = new Headers({ 'Content-Type': 'application/json' });

            return this.http.post(url, data, { headers: headers })
                  .map(this.extractData)
                  .catch(this.handleError);
      }

      //表单提交
      postForm(url, data): Observable<any> {
            //设置头
            let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });

            return this.http.post(url, data, { headers: headers })
                  .map(this.extractData)
                  .catch(this.handleError);
      }

      //成功
      private extractData(res: Response) {
            let body = res.json();
            return body.data || body;
      }

      //失败
      private handleError(error: Response | any) {
            // In a real world app, you might use a remote logging infrastructure
            let errMsg: string;
            if (error instanceof Response) {
                  // const body = error.json() || '';
                  const err = error || JSON.stringify(error);
                  errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
            } else {
                  errMsg = error.message ? error.message : error.toString();
            }
            console.error(errMsg);
            return Observable.throw(errMsg);
      }


}
